﻿using System;
using System.Collections.Generic;
using System.Xml;

namespace SocialFilter.controller
{
	// Singleton
	static class ConfigurationController
	{
		private static Dictionary<string, string> configurations;

		public static void Initialize()
		{
			configurations = new Dictionary<string,string>();
			SetConfiguration("config", "../../config.xml");
		}

		public static void LoadConfiguration()
		{
			string configName;
			if (null != (configName = GetConfiguration("config")))
			{
				LoadConfiguration(configName);
			}
			else
			{
				LoadConfiguration("config.xml");
			}
		}

		public static void LoadConfiguration(string _fileName)
		{
			//clear current configuration
			ResetConfigurations();
			
			// parse config
			XmlTextReader reader = new XmlTextReader( _fileName );
			reader.WhitespaceHandling = WhitespaceHandling.None;
			
			while ( reader.Read() )
			{
				if ( reader.Name != "" && reader.HasAttributes )
				{
					SetConfiguration(reader.Name, reader.GetAttribute("value"));
				}
			}
			
			reader.Close();
		}

		public static void WriteConfiguration()
		{
			string configName;
			if ( null != ( configName = GetConfiguration("config") ) )
			{
				WriteConfiguration(configName);
			}
			else
			{
				WriteConfiguration("config.xml");
			}
		}

		public static void WriteConfiguration(string _fileName)
		{
			//TODO: write config
		}

		public static string GetConfiguration(string _variableName)
		{
			if ( configurations.ContainsKey(_variableName) )
			{
				return configurations[_variableName];
			}
			else
			{
				return null;
			}
		}

		public static void SetConfiguration(string _variableName, string _value)
		{
			configurations[_variableName] = _value;
		}

		private static void ResetConfigurations()
		{
			string configName = GetConfiguration("config");
			configurations.Clear();
			if ( configName != null )
			{
				SetConfiguration("config", configName);
			}
		}
	}
}
